package com.mjh.task;

import java.util.ArrayList;
import java.util.HashMap;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import com.mjh.manager.*;
import com.mjh.util.FreeMarkerUtil;
import com.mjh.bean.Category;
import com.mjh.comm.*;

public class HomePageMaker implements Job{
	
	private static final String homePageTemplate = "WEB-INF/templates/homePage.html";
	private static final String outputFile = Constant.SERVLET_CONTEXT + "index.html";
	
	private static Logger log = Logger.getLogger(HomePageMaker.class);
	
	private ArticleManager manager = new ArticleManager();
	
	public void execute(JobExecutionContext context) throws JobExecutionException {
		
		String jobName = context.getJobDetail().getName();
		TaskManager.getInstance().setTaskLastExcuteDate(jobName, context.getFireTime());
		TaskManager.getInstance().setTaskNextExcuteDate(jobName, context.getNextFireTime());
		
		//显示各个栏目最新的文章
		HashMap<String,Object> categoryArticlesMap;
		ArrayList<HashMap<String,Object>> categoryArticles = new ArrayList<HashMap<String,Object>>();
		ArrayList<Category> categorys = new CategoryConfigManager().listCategory();
		for(Category cat : categorys){
			if(cat.getSubCategory() != null && cat.getSubCategory().size() > 0){
				categoryArticlesMap = new HashMap<String,Object>();
				categoryArticlesMap.put("category", cat);
				categoryArticlesMap.put("articles", manager.listByCategory(NumberUtils.toInt(cat.getId()), 5));
				categoryArticles.add(categoryArticlesMap);
			}
		}

		HashMap<String,Object> parameter = new HashMap<String, Object>();
		parameter.put("categoryArticlesList", categoryArticles);
		int result = FreeMarkerUtil.processToFile(parameter, homePageTemplate, outputFile);
		TaskManager.getInstance().setTaskLastExcuteState(jobName, result);
		
		log.info("生成首页 " + Constant.OPERATE_DESC[result]);
	}

}
